<template>
    <div
        class="h-full w-full flex flex-col font-px bg-no-repeat bg-center bg-cover"
        :style="{ backgroundImage: `url(${backgroundURL})` }"
    >
        <header class="bg-zinc-50 h-16 flex py-2 px-8 items-end">
            <div class="text-2xl flex items-end">
                <b>像素画板</b>
                <span class="text-sm px-2 mx-2 bg-zinc-100 rounded">ProPixel</span>
            </div>
            <div class="flex-grow">
                <Icon class="icon" v-if="selectMode" @pointerdown="deleteFiles">delete</Icon>
            </div>
            <div class="mx-4 grid grid-flow-col gap-2 text-xl text-zinc-600">
                <Add @createFile="openedName = 'CreateFile'"></Add>
                <!--  暂不支持文件夹 -->
                <!-- <Icon>create_new_folder</Icon> -->
                <Icon
                    class="icon"
                    @pointerdown="selectMode = !selectMode"
                    :class="[selectMode && 'bg-zinc-300']"
                >view_week</Icon>
                <settingVue></settingVue>
            </div>
            <nav v-if="store.user">{{ store.user.userName }}</nav>
        </header>
        <main class="flex-grow bg-zinc-200/80">
            <nav
                v-if="store.preview.length === 0"
                class="h-full w-full text-center text-3xl text-white flex place-items-center justify-center"
                @pointerdown="changeKaomoji"
            >这里什么也没有哦 {{ Kaomoji }}</nav>
            <div
                v-else
                class="grid grid-cols-2 lg:grid-cols-6 md:grid-cols-5 sm:grid-cols-4 place-items-center px-8 py-4 gap-2 cursor-pointer"
            >
                <div
                    class="col-span-1 w-full h-full p-4 grid grid-rows-4 gap-2 rounded-lg transition-all"
                    v-for="preview in store.preview"
                    :class="[selectedFile.includes(preview.id) && 'bg-zinc-100 shadow-lg ']"
                    @pointerdown="clickFile(preview.id)"
                >
                    <VanImage
                        lazy-load
                        fit="cover"
                        position="center"
                        class="h-full w-full bg-white rounded-lg overflow-hidden outline outline-white outline-1 shadow row-span-3"
                        :src="preview.image"
                    ></VanImage>
                    <div>
                        <b>{{ preview.name }}</b>
                        <div class="text-xs italic">{{ preview.width }}x{{ preview.height }}</div>
                    </div>
                </div>
            </div>
        </main>
        <footer class="flex items-center px-4 bg-zinc-50">
            <b class="text-sm">/root</b>
            <span class="flex-grow"></span>
            <Icon>replay</Icon>
        </footer>
        <component v-if="opening" :is="opening" @close="openedName = null"></component>
    </div>
</template>

<style scoped>
.icon {
    @apply p-1 rounded;
}
</style>

<script lang="ts" setup>
import Icon from "@konghayao/vue-material-icons";
import { Dialog, Toast } from "vant";
import { useRouter } from "vue-router";
import { Image as VanImage } from 'vant'
import Add from './Files/Add.vue'
import { useFileStore } from './Files/files'
import CreateFile from "./Files/createFile.vue";
import { computed, onMounted, ref, onUnmounted, watch, nextTick, reactive } from "vue";
import { randomKaomoji } from "../../package/kaomoji";
import settingVue from "./Files/setting.vue";
import { useSettingStore, settingHub, SettingUpdated } from "./Files/store/setting";
const Setting = useSettingStore()

// 背景图设置
const backgroundURL = ref('')
onMounted(() => {
    backgroundURL.value = Setting.getDataURL('backgroundImage')
})
const updateBackground = (a: SettingUpdated) => {
    if ("backgroundImage" in a) {
        URL.revokeObjectURL(backgroundURL.value)
        backgroundURL.value = Setting.getDataURL('backgroundImage')
    }
}
settingHub.on('update', updateBackground)

onUnmounted(() => {
    URL.revokeObjectURL(backgroundURL.value)
    settingHub.off('update', updateBackground)
})

// 登录用户并获取数据
const store = useFileStore()
store.loginUser().then((result) => {
    if (result) {
        Toast({
            message: `您好，${store.user!.userName}`,
            position: 'bottom'
        })
    }
}).then(store.loadPreview).then(() => {
    store.ready = true
})


// 打开文件时的跳转的操作
const router = useRouter()
const openFile = async (id: string) => {
    await store.openFile(id)
    router.push({
        path: `/editor/${id}`
    })
}
/** 多选文件 */
const selectMode = ref(false)

watch(selectMode, (val) => {
    if (val === false) selectedFile.length = 0
})

const selectedFile = reactive<string[]>([])
const clickFile = (id: string) => {
    if (selectMode.value) {
        const index = selectedFile.indexOf(id)
        if (index === -1) {
            selectedFile.push(id)
        } else {
            selectedFile.splice(index, 1)
        }
    } else {
        openFile(id)
    }
}

const deleteFiles = () => {
    Dialog.confirm({
        closeOnClickOverlay: true,
        title: "删除操作！", message: `是否删除 ${selectedFile.length} 个文件？`
    }).then(() => {

        selectedFile.reduce(async (col, i) => {
            return col.then(() => store.deleteFile(i))
        }, Promise.resolve())
    }, () => { Toast({ position: "bottom", message: "取消删除" }) })
}

// 浮窗监控
const overlays = {
    CreateFile
}
const openedName = ref<(keyof typeof overlays) | null>(null)
const opening = computed(() => {
    if (openedName.value) {
        return overlays[openedName.value]

    } else {
        return null
    }
})

// 随机表情符号
const Kaomoji = ref('')
const changeKaomoji = () => Kaomoji.value = randomKaomoji()
changeKaomoji()
</script>